<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <el-icon
          :size="48"
          color="#1890ff"
        >
          <House />
        </el-icon>
        <h1>房产CRM管理系统</h1>
        <p>AI驱动的客户关系管理平台</p>
      </div>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        size="large"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="formData.username"
            placeholder="请输入用户名或邮箱"
            prefix-icon="User"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="formData.remember">
            记住我（30天内自动登录）
          </el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            style="width: 100%"
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>

      <div class="login-footer">
        <div style="margin-bottom: 8px">
          <el-link
            type="primary"
            @click="goToPasswordReset"
          >
            忘记密码？
          </el-link>
        </div>
        <span>演示账号: Administrator / admin123</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
defineOptions({ name: 'LoginPage' })
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import type { FormInstance, FormRules } from 'element-plus'
import notify from '@/utils/notify'
import { logger } from '@/utils/logger'

const router = useRouter()
const userStore = useUserStore()

// 表单数据
const formData = reactive({
  username: '',
  password: '',
  remember: false, // 记住我选项
})

// 表单验证规则
const rules: FormRules = {
  username: [{ required: true, message: '请输入用户名或邮箱', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' },
  ],
}

const formRef = ref<FormInstance>()
const loading = ref(false)

// 登录处理
const handleLogin = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return

    loading.value = true
    try {
      logger.debug('Login form submitted', { username: formData.username })
      // 自动去除用户名和密码的首尾空格
      const loginData = {
        username: formData.username.trim(),
        password: formData.password.trim(),
        remember: formData.remember,
      }
      const success = await userStore.login(loginData)
      logger.debug('Login result', { success })
      if (success) {
        notify.success('登录成功')
        logger.debug('Redirecting to smart-import')
        await router.push('/smart-import')
        logger.debug('Navigation completed')
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error)
      logger.error('Login process failed', { errorMessage })
    } finally {
      loading.value = false
    }
  })
}

// 跳转到密码重置页面
const goToPasswordReset = () => {
  router.push('/password-reset')
}
</script>

<style scoped>
.login-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-box {
  width: 400px;
  padding: 40px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.login-header h1 {
  margin: 16px 0 8px;
  font-size: 24px;
  color: #333;
}

.login-header p {
  margin: 0;
  font-size: 14px;
  color: #999;
}

.login-footer {
  margin-top: 24px;
  text-align: center;
  font-size: 12px;
  color: #999;
}
</style>
